
#include "XmlTable.h"
#include "Common/Strings.h"

//----------------
//--- XmlTable ---
//----------------

using namespace ttg_internal;
using namespace ttg::structures;
using namespace ttg::extras;

XmlTable::XmlTable()
{
	this->base = NULL;
}

XMLTree *XmlTable::get(const char *name)
{
	XmlTableNode *node = base->get(name);
	if (node != NULL)
	{
		return &(base->get(name)->getXml()->getSubXMLTree());
	}
	else
		return NULL;
}

void XmlTable::assign(const char *filename, const char *path, const char *comparername)
{
	//Loading and preparing xml.
	xml.assign(XMLTree::XML_RO, filename);
	strings::StringSplitter sp;
	sp.setSplitter('/',  false);
	sp.setSplitter('\\', false);
	sp.setSplitter(' ', false);
	sp.setString(path);
	for (size_t i = 0; i < sp.getCount(); i++)
	{
		if (!xml.openSection(sp[i]))
		{
			throw Error(Error::LOCAL, "XmlTable", "assign",
						"Cannot find section by path", path);
		}
	}
	//Creating and filling base and refs.
	this->base = Dictionary<XmlTableNode>::create(xml.getSubSectionCount());
	while (xml.openNextSection())
	{
		const char *val;
		if (!xml.getStringAttribute(comparername, val))
		{
			SAFE_DELETE(base);
			throw Error(Error::LOCAL, "XmlTable", "assign",
						"Cannot find comparer-attribute", comparername);
		}
		XMLTree *ss = &xml.getSubXMLTree();
		base->add(new XmlTableNode(strings::clearStartEndSpaces(val).c_str(), ss));
		refs.push_back(ss);
		xml.closeSection();
	}

}

void XmlTable::close()
{
	refs.clear();
	SAFE_DELETE(base);
	xml.close();
}

XmlTable::~XmlTable()
{
	this->close();
}
